{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "709fc5b2",
   "metadata": {},
   "source": [
    "## 百度AI开放平台\n",
    "> 1. 首先在百度AI控制台 创建对应的api应用并获取相应的api_key & api_secret\n",
    "> 2. 直接复制[鉴权机制](https://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjhhu)的代码,并粘贴到python中来，记得选择python的模式\n",
    "> 3. 打开技术文档，复制里面的参考代码，并粘贴到python中，记得选择pytho的版本"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f7ad39f",
   "metadata": {},
   "source": [
    "### 鉴权认证机制（Access_Token）\n",
    "* 获取Access Token\n",
    "* 获取access_token示例代码:\n",
    "---\n",
    "\n",
    "```\n",
    "encoding:utf-8\n",
    "import requests \n",
    "client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【官网获取的AK】&client_secret=【官网获取的SK】'\n",
    "response = requests.get(host)\n",
    "if response:\n",
    "    print(response.json())\n",
    "```\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "e93294ff",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.62a8c4eda0caeb1e8026526479b2582e.315360000.1965124775.282335-25954401', 'expires_in': 2592000, 'session_key': '9mzdDAFsPll9TW8BmyiVu3AmFs5Gd/CVXzHyFHhSXhC3Dt9A7Vad4Xwkxs0LzdgrNF7cQMYkCH/Dm9vD4Mip92vbn8yj6A==', 'access_token': '24.74c663a5f50e3dbaee4c94e0fcfd12e3.2592000.1652356775.282335-25954401', 'scope': 'public vis-classify_dishes vis-classify_car brain_all_scope vis-classify_animal vis-classify_plant brain_object_detect brain_realtime_logo brain_dish_detect brain_car_detect brain_animal_classify brain_plant_classify brain_ingredient brain_advanced_general_classify brain_custom_dish brain_poi_recognize brain_vehicle_detect brain_redwine brain_currency brain_vehicle_damage brain_multi_ object_detect wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online', 'session_secret': '81fadf97155682ac5189c042ca972311'}\n"
     ]
    }
   ],
   "source": [
    "# 对上面复制下来的代码进行修改\n",
    "# encoding:utf-8\n",
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?'\n",
    "# 利用酬载\n",
    "payload = {\n",
    "    'grant_type':'client_credentials',\n",
    "    'client_id':'4k3n6KCvXm82QtQ6qBqrSLbD',\n",
    "    'client_secret':'CfXuUIMKtzIPs3gwGGVbZSyKcRID3Yur'\n",
    "}\n",
    "response = requests.get(host,params=payload)\n",
    "if response:\n",
    "    print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "8a1401e4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'24.74c663a5f50e3dbaee4c94e0fcfd12e3.2592000.1652356775.282335-25954401'"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 对获取到的at进行简易的存储\n",
    "qt_at = response.json()['access_token']\n",
    "qt_at"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9784c853",
   "metadata": {},
   "source": [
    "* 请求参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "5caa58e3",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "d0b054b9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>参数</th>\n",
       "      <th>是否必选</th>\n",
       "      <th>类型</th>\n",
       "      <th>可选值范围</th>\n",
       "      <th>说明</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>image</td>\n",
       "      <td>和url二选一</td>\n",
       "      <td>string</td>\n",
       "      <td>-</td>\n",
       "      <td>图像数据，base64编码，要求base64编码后大小不超过4M，最短边至少15px，最长边...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>url</td>\n",
       "      <td>和image二选一</td>\n",
       "      <td>string</td>\n",
       "      <td>-</td>\n",
       "      <td>图片完整URL，URL长度不超过1024字节，URL对应的图片base64编码后大小不超过4...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>baike_num</td>\n",
       "      <td>否</td>\n",
       "      <td>integer</td>\n",
       "      <td>-</td>\n",
       "      <td>返回百科信息的结果数，默认不返回</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "          参数       是否必选       类型 可选值范围  \\\n",
       "0      image    和url二选一   string     -   \n",
       "1        url  和image二选一   string     -   \n",
       "2  baike_num          否  integer     -   \n",
       "\n",
       "                                                  说明  \n",
       "0  图像数据，base64编码，要求base64编码后大小不超过4M，最短边至少15px，最长边...  \n",
       "1  图片完整URL，URL长度不超过1024字节，URL对应的图片base64编码后大小不超过4...  \n",
       "2                                   返回百科信息的结果数，默认不返回  "
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 图像识别 url ： https://ai.baidu.com/ai-doc/IMAGERECOGNITION/Xk3bcxe21\n",
    "pd.read_html('https://ai.baidu.com/ai-doc/IMAGERECOGNITION/Xk3bcxe21')[2]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ab59ec6a",
   "metadata": {},
   "source": [
    "### 通用物体和场景识别\n",
    "* 示例代码\n",
    "---\n",
    "```\n",
    "# encoding:utf-8\n",
    "import requests\n",
    "import base64\n",
    "'''\n",
    "通用物体和场景识别\n",
    "'''\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('[本地文件]', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "params = {\"image\":img}\n",
    "access_token = '[调用鉴权接口获取的token]'\n",
    "request_url = request_url + \"?access_token=\" + access_token\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=params, headers=headers)\n",
    "if response:\n",
    "    print (response.json())\n",
    "```\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e1333dc6",
   "metadata": {},
   "source": [
    "> 1. 问题 ： {'error_code': 18, 'error_msg': 'Open api qps request limit reached'}\n",
    "> 2. 解决办法 : \n",
    ">>1. [延迟访问频率](https://blog.csdn.net/weixin_41453476/article/details/106615353)\n",
    ">>2. [查看是否领取了免费的额度](https://blog.csdn.net/weixin_44298740/article/details/117560495)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "27ed0480",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result_num': 5, 'result': [{'keyword': '吸顶灯', 'score': 0.707037, 'root': '商品-家居家装'}, {'keyword': '卡通动漫人物', 'score': 0.496897, 'root': '非自然图像-彩色动漫'}, {'keyword': '图画', 'score': 0.305728, 'root': '商品-绘画'}, {'keyword': '灯', 'score': 0.153614, 'root': '商品-灯具'}, {'keyword': '室内一角', 'score': 0.002187, 'root': '建筑-室内'}], 'log_id': 1513849887699911982}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "import time\n",
    "\n",
    "\n",
    "'''\n",
    "通用物体和场景识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('kanekikeh.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "params = {\"image\":img}\n",
    "access_token = qt_at\n",
    "request_url = request_url + \"?access_token=\" + access_token\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=params, headers=headers)\n",
    "if response:\n",
    "    time.sleep(1)\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c9681e37",
   "metadata": {},
   "source": [
    "### 菜品识别\n",
    "* 在正式使用自定义菜品识别-检索服务前需要申请建库，建库后方可使用\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "6a0866da",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result_num': 5, 'result': [{'calorie': '109', 'has_calorie': True, 'name': '凉皮', 'probability': '0.772002'}, {'calorie': '38', 'has_calorie': True, 'name': '凉粉', 'probability': '0.145779'}, {'calorie': '198', 'has_calorie': True, 'name': '油泼面', 'probability': '0.020761'}, {'calorie': '208', 'has_calorie': True, 'name': '热面皮', 'probability': '0.0172021'}, {'calorie': '120', 'has_calorie': True, 'name': '刀削面', 'probability': '0.00660493'}], 'log_id': 1513852300133253194}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "菜品识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/dish\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('remipi.png', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "params = {\"image\":img,\"top_num\":5}\n",
    "access_token = qt_at\n",
    "request_url = request_url + \"?access_token=\" + access_token\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=params, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cd1eebce",
   "metadata": {},
   "source": [
    "### 植物识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "7ef6ee5b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result': [{'name': '千佛手', 'score': 0.85211605}, {'name': '翡翠景天', 'score': 0.34213796}, {'name': '瓦松', 'score': 0.17248873}], 'log_id': 1513854297562741192}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "植物识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v1/plant\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('多肉.png', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "params = {\"image\":img}\n",
    "access_token = qt_at\n",
    "request_url = request_url + \"?access_token=\" + access_token\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=params, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dc25031c",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dde411b8",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "826e7534",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "732bd3ab",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5a1aa766",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
